'use strict'

const { InvalidQueryError } = require('../lib/error');
const qnTemplateServices = require('../services').qnTemplate;
const UUID = require('uuidjs');
const dayjs = require('dayjs');

const qnTemplate = {
  async saveTemplate(ctx, next) {
    const params = ctx.request.body;
    const result = await qnTemplateServices.saveTemplate(params)
    const res = await qnTemplate.handleSaveProject(result)
    ctx.result = res
    return next()
  },
  async handleSaveProject(params) {
    const {templateId, title} = params;
    // const name = title.replace(/^\<p\>/, '').replace(/\<\/p\>$/, '');
    const rex =  /(<([^>]+)>)/ig
    const name = title.replace(rex, '')
    const data = {
      templateId,
      name,
      id: UUID.genV4().hexFields[5],
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      userName: 'Unknow',
      count: 0,
      state: false,
    }
    return qnTemplateServices.saveProject(data);
  },
  async saveProject(ctx, next) {
    const params = ctx.request.body;
    const res = await qnTemplateServices.saveProject(params);
    ctx.result = res;
    return next()
  },

  async findTemplateState(ctx, next) {
    const params = ctx.request.body;
    const res = await qnTemplateServices.findTemplateState(params)
    ctx.result = res;
    return next();
  },
  async changeTemplateState(ctx, next) {
    const params = ctx.request.body;
    const res = await qnTemplateServices.changeTemplateState(params)
    ctx.result = res;
    return next();
  },

  async findTemplate(ctx, next) {
    const params = ctx.request.body;
    const { templateId } = params;
    if (!templateId) {
      throw new InvalidQueryError()
    }
    const res = await qnTemplateServices.findTemplate({templateId})
    ctx.result = res
    return next()
  },
  
  async findQn(ctx, next) {
    const params = ctx.request.body;
    const { templateId } = params;
    if (!templateId) {
      throw new InvalidQueryError()
    }
    const stateRes = await qnTemplateServices.findTemplateState({templateId});
    if (stateRes && stateRes.state) {
      const res = await qnTemplateServices.findTemplate({templateId})
      ctx.result = res
    } else {
      ctx.result = {}
    }
    return next()
  },
  async findTemplateList(ctx, next) {
    const params = ctx.request.body;
    const { pageSize, currentPage } = params;
    if (!pageSize || !currentPage) {
      throw new InvalidQueryError()
    }
    const res = await qnTemplateServices.findTemplateList({pageSize, currentPage})
    ctx.result = res
    return next()
  }
  
}

module.exports = qnTemplate